﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZX.Web.UI.Controls;
using ZX.SYS.Bussiness;
using System.Data;
using ZX.BLL.Extend;
using ZX.EHR.Library;
using ZX.DBModule;
using ZX.BLL;
using System.Web.Security;
using ZX.SYS.Library;
using System.Text.RegularExpressions;
using System.Configuration;
using System.IO;
using System.Net;
using System.Xml;
using System.Drawing;
using System.Text;
namespace ZX.WebApp.Message
{
    public partial class MmsEdit : BasePage
    {
        public static readonly string fileurl = ConfigurationManager.AppSettings["filepath"].ToString();
        public static readonly string picurl = ConfigurationManager.AppSettings["picurl"].ToString();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                string title = Request.QueryString["title"];
                if (title == null)//新增，创建文件夹
                {
                    string fpn = DateTime.Now.ToString("yyyyMMddHHmmss");
                    if (!Directory.Exists(Server.MapPath(fileurl + fpn)))
                    {
                        hdffilepathname.Value = fpn;
                        Directory.CreateDirectory(Server.MapPath(fileurl + fpn));
                    }
                    else
                    {
                        hdffilepathname.Value = fpn + DateTime.Now.Second.ToString();
                        Directory.CreateDirectory(Server.MapPath(fileurl + hdffilepathname.Value));
                    }
                }
                else//编辑
                {
                    //获得数据，分解出文件夹信息
                    MmsProccess mp = new MmsProccess();
                    DataTable dt = mp.getmmsmessage(new Guid(Request.QueryString["id"]));
                    string filepathn = "";
                    string[] strpurs = {};
                    if (dt.Rows.Count > 0)
                    {
                        txttitle.Text = dt.Rows[0]["mtitle"].ToString();
                        strpurs= dt.Rows[0]["purtimes"].ToString().Split(';');
                        filepathn=strpurs[0];
                        hdffilepathname.Value = filepathn;
                        
                    }
                    FileInfo fi = new FileInfo(Server.MapPath(fileurl + hdffilepathname.Value + "/1.xml"));
                    labfiledaxiao.Text = (fi.Length / 1000).ToString() + "K";

                    if (Directory.Exists(Server.MapPath(fileurl + filepathn)))
                    {
                        string fpathif = Server.MapPath(fileurl + filepathn + "/");
                        for (int i = 1; i < strpurs.Length; i++)
                        {
                            string imgpath = "";
                            string audpath = "";
                            string txtpath = "";
                            if (File.Exists(fpathif + i + ".jpg"))
                            {
                                imgpath = fileurl + filepathn + "/" + i + ".jpg";
                            }
                            else if (File.Exists(fpathif + i + ".gif"))
                            {
                                imgpath = fileurl + filepathn + "/" + i + ".gif";
                            }

                            if (File.Exists(fpathif + i + ".mid"))
                            {
                                audpath = i + ".mid";
                            }
                            else if (File.Exists(fpathif + i + ".amr"))
                            {
                                audpath = i + ".amr";
                            }

                            if (File.Exists(fpathif + i + ".txt"))
                            {
                                StringBuilder b = new StringBuilder();
                                using (FileStream fs = new FileStream(fpathif + i + ".txt", FileMode.Open))
                                {
                                    using (StreamReader sr = new StreamReader(fs))
                                    {
                                        while (!sr.EndOfStream)
                                        {
                                            string sLine = sr.ReadLine();
                                            if (sLine.Length < 1)
                                            {
                                                continue;
                                            }
                                            b.Append(sLine);
                                        }
                                    }
                                }
                                txtpath = b.ToString();
                            }

                            System.Web.UI.HtmlControls.HtmlTextArea ta = this.FindControl("loadtxt" + i) as System.Web.UI.HtmlControls.HtmlTextArea;
                            System.Web.UI.HtmlControls.HtmlTextArea tat = this.FindControl("con_txt_" + i) as System.Web.UI.HtmlControls.HtmlTextArea;
                            System.Web.UI.HtmlControls.HtmlInputText tx = this.FindControl("txtbbs" + i) as System.Web.UI.HtmlControls.HtmlInputText;
                            System.Web.UI.HtmlControls.HtmlImage im = this.FindControl("loadimg" + i) as System.Web.UI.HtmlControls.HtmlImage;
                            TextBox tb = this.FindControl("tbaudio" + i) as TextBox;
                            HiddenField hdf = this.FindControl("hdfimgpath" + i) as HiddenField;
                            hdf.Value = imgpath;
                            tat.Value = txtpath;
                            ta.Value = txtpath;
                            tb.Text = audpath;
                            tx.Value=strpurs[i];
                        }
                    }
                }
                }
        }
        protected void btnsave_Click(object sender, EventArgs e)
        {
            //创建
            XmlDocument xmldoc;
            XmlElement xmlelem;

            xmldoc = new XmlDocument();
            XmlDeclaration xmldecl;
            xmldecl = xmldoc.CreateXmlDeclaration("1.0", "utf-8", null);
            xmldoc.AppendChild(xmldecl);

            //加入一个根元素   
            xmlelem = xmldoc.CreateElement("", "Body", "");
            xmldoc.AppendChild(xmlelem);

            XmlNode root = xmldoc.SelectSingleNode("Body");//查找<Body> 
            XmlElement amm = xmldoc.CreateElement("mms");
            root.AppendChild(amm);

            XmlNode mms = root.SelectSingleNode("mms");
            XmlElement sbj = xmldoc.CreateElement("","subject","");
            sbj.InnerText = EncodeBase64("UTF-8", txttitle.Text);
            XmlElement rgt =xmldoc.CreateElement("regulartime");
            rgt.InnerText = "";// DateTime.Now.ToString();
            XmlElement pgs = xmldoc.CreateElement("pages");
            mms.AppendChild(sbj);
            mms.AppendChild(rgt);
            mms.AppendChild(pgs);

            XmlNode pages = mms.SelectSingleNode("pages");
            StringBuilder sbpur = new StringBuilder();
            sbpur.Append(hdffilepathname.Value);//记录文件夹名称
            for (int i = 1; i < 11; i++)
            {
                System.Web.UI.HtmlControls.HtmlTextArea ta = this.FindControl("loadtxt"+i) as System.Web.UI.HtmlControls.HtmlTextArea;
                System.Web.UI.HtmlControls.HtmlInputText tx = this.FindControl("txtbbs" + i) as System.Web.UI.HtmlControls.HtmlInputText;
                System.Web.UI.HtmlControls.HtmlImage im = this.FindControl("loadimg" + i) as System.Web.UI.HtmlControls.HtmlImage;
                TextBox tb=this.FindControl("tbaudio"+i) as TextBox;
                HiddenField hdf = this.FindControl("hdfimgpath"+i) as HiddenField;
                im.Src = hdf.Value;
                string fn=hdf.Value;
                if (ta.Value == "" && im.Src == "")
                {
                    break;
                }
                else
                {
                    XmlElement pg = xmldoc.CreateElement("page");//创建一个<page>节点    
                    pg.SetAttribute("dur", tx.Value);//设置该节点dur属性 
                    sbpur.Append(";" + tx.Value);
                    pg.SetAttribute("order", i.ToString());//设置该节点order属性    

                    XmlElement txt = xmldoc.CreateElement("text");
                    txt.SetAttribute("type", "txt");
                    txt.InnerText = EncodeBase64("GBK", ta.Value);
                    if(i!=1)
                         pg.AppendChild(txt);
                    //文本节点
                    string txtfile = Server.MapPath(fileurl + hdffilepathname.Value + "/" + i + ".txt");
                    //c#创建txt 并填写
                    if (!File.Exists(txtfile))
                    {
                        FileStream fs1 = new FileStream(txtfile, FileMode.Create, FileAccess.Write);//创建写入文件 
                        StreamWriter sw = new StreamWriter(fs1);
                        sw.WriteLine(ta.Value);//开始写入值
                        sw.Close();
                        fs1.Close();
                    }
                    else
                    {
                        FileStream fs = new FileStream(txtfile, FileMode.Open, FileAccess.Write);
                        StreamWriter sr = new StreamWriter(fs);
                        sr.WriteLine(ta.Value);//开始写入值
                        sr.Close();
                        fs.Close();
                    }
                    //图片节点
                    if (fn != "")
                    {
                        string fname = "";
                        int l = fn.Length;
                        if (l > 5)
                        {
                            fname = fn.Substring(l - 4);
                        }
                        byte[] data = File.ReadAllBytes(Server.MapPath(fileurl + hdffilepathname.Value + "/" + i + fname));
                        string imgdata = Convert.ToBase64String(data);

                        XmlElement pic = xmldoc.CreateElement("img");
                        pic.SetAttribute("type", fn.Substring(l - 3));
                        pic.InnerText = imgdata;
                        pg.AppendChild(pic);
                    }
                    if (tb.Text != "")
                    {
                        XmlElement aud = xmldoc.CreateElement("audio");
                        aud.SetAttribute("type", tb.Text.Substring(tb.Text.Length - 3));

                        byte[] data = File.ReadAllBytes(Server.MapPath(fileurl + hdffilepathname.Value + "/" + tb.Text));
                        string auddata = Convert.ToBase64String(data);
                        aud.InnerText = auddata;
                        pg.AppendChild(aud);
                    }
                    pages.AppendChild(pg);//添加到<pages>节点中
                }
            }

            //保存创建好的XML文档   
            using (XmlTextWriter xtw = new XmlTextWriter(Server.MapPath(fileurl + hdffilepathname.Value + "/1.xml"), null))
            {
                xtw.Formatting = Formatting.None;
                xmldoc.Save(xtw);
            }

            MmsProccess mp = new MmsProccess();
            string fp111 = hdffilepathname.Value;
            DataTable dtids= mp.getmmsifexist(fp111);
            if (dtids.Rows.Count>0)
            {
                Guid mmsid = new Guid(dtids.Rows[0][0].ToString());
                mp.editmms(mmsid, txttitle.Text, sbpur.ToString());
            }
            else
            {
                mp.insert(txttitle.Text, sbpur.ToString(), User.UserID);
            }

        }


        #region Base64编码与解码
        /// <summary>
        /// Base64编码
        /// </summary>
        /// <param name="code_type">字符串编码类型</param>
        /// <param name="code">需要Base64编码的字符串</param>
        /// <returns>经过Base64编码的字符串</returns>
        private string EncodeBase64(string code_type, string code)
        {
            string encode = "";
            byte[] bytes = System.Text.Encoding.GetEncoding(code_type).GetBytes(code);
            try
            {
                encode = Convert.ToBase64String(bytes);
            }
            catch
            {
                encode = code;
            }
            return encode;
        }

        /// <summary>
        /// Base64解码
        /// </summary>
        /// <param name="code_type">字符串解码类型</param>
        /// <param name="code">需要Base64解码的字符串</param>
        /// <returns>经过Base64解码的字符串</returns>
        private string DecodeBase64(string code_type, string code)
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(code);
            try
            {
                decode = Encoding.GetEncoding(code_type).GetString(bytes);
            }
            catch
            {
                decode = code;
            }
            return decode;
        }

      
        #endregion
    }
}